package com.example.service.webhook.business.email.service;

import com.example.service.webhook.business.email.api.EmailClient;
import com.example.service.webhook.business.email.billitem.EmailBillTask;
import com.example.service.webhook.business.email.dto.EmailBill;
import com.example.service.webhook.business.email.dto.EmailBillInstallment;
import com.example.service.webhook.business.email.dto.EmailBillList;
import com.example.service.webhook.business.email.dto.EmailBillShoppingSheet;
import com.example.service.webhook.business.email.entity.EmailBillEntity;
import com.example.service.webhook.business.email.entity.EmailBillInstallmentEntity;
import com.example.service.webhook.business.email.entity.EmailBillShoppingSheetEntity;
import com.example.service.webhook.business.email.repository.BillInstallmentRepository;
import com.example.service.webhook.business.email.repository.BillRepository;
import com.example.service.webhook.business.email.repository.BillShoppingSheetRepository;
import com.example.service.webhook.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
/**
 * 邮箱账单处理类
 * 1、账单
 * 2、消费记录
 * 3、分期记录
 * ClassName: BillService    
 * date: 2016年7月20日 下午5:35:35   
 * @author yuandong  
 * @version   
 * @since JDK 1.6
 *
 *
 * Modified by liyang on 20171019 接口升级
 */
@Service
public class BillService {
	private static final Logger LOGGER = LoggerFactory.getLogger(BillService.class);

	@Autowired
	private EmailClient emailClient;

	@Autowired
	private BillRepository billRepository;

	@Autowired
	private BillShoppingSheetRepository billShoppingSheetRepository;

	@Autowired
	private BillInstallmentRepository billInstallmentRepository;

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;


	/**
	 * fetchBill:处理邮箱下面的所有账单 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * for(保存账单){ 保存单条账单 －保存消费记录 －保存分期记录 }<br/>
	 *
	 * @param task
	 * @author yuandong
	 * @since JDK 1.6
	 */
	public void fetchBill(final EmailBillTask task) {
		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求

		taskExecutor.execute(
				new Runnable() {
					@Override
					public void run() {
						try {
							/**
							 * 20171019接口升级，根据taskId获取账单信息
							 */
							String taskId = task.getTaskId();
							if (task.getBillCount() > 0) {
								// 查询所有账单
								List<EmailBill> emailBills = loadBillByCallApi(taskId);
								LOGGER.info("emailBills size:" + emailBills.size());
								if (emailBills != null && !emailBills.isEmpty()) {
									for (EmailBill emailBill : emailBills) {
										EmailBillEntity billEntity = new EmailBillEntity();
										BeanUtils.copyProperties(emailBill, billEntity);
										billEntity.setUserId(task.getUserId());
										// 判断此账单是否存在（billId是账单的唯一标识）
										EmailBillEntity existBill = billRepository.getTBillById(emailBill.getBillId());
										if (existBill != null) {
											// 账单存在，则更新。这里根据自己的业务来，更新可以不做。
											billEntity.setLastModifyTime(DateUtil.getCurrentDate());
											billRepository.modify(billEntity);
										} else {
											// 账单不存在，保存账单
											billRepository.saveBill(billEntity);

											//先执行一次删除，防止已经有消费记录了
											billShoppingSheetRepository.deleteShoppingSheetByBillId(billEntity.getBillId(), task.getUserId());
											List<EmailBillShoppingSheet> shoppingSheets = emailBill.getShoppingSheets();
											if (null != shoppingSheets || shoppingSheets.size() > 0) {
												for (EmailBillShoppingSheet sheet : shoppingSheets) {
													EmailBillShoppingSheetEntity sheetEntity = new EmailBillShoppingSheetEntity();
													BeanUtils.copyProperties(sheet, sheetEntity);
													sheetEntity.setUserId(task.getUserId());
													sheetEntity.setEmailId(task.getEmailId());
													billShoppingSheetRepository.saveBillShoppingSheet(sheetEntity, sheetEntity.getUserId());
												}
											}

											//保存之前删除分期记录
											billInstallmentRepository.deleteInstallmentByBillId(emailBill.getBillId());
											List<EmailBillInstallment> installments = emailBill.getInstallments();
											if (null != installments || installments.size() > 0) {
												for (EmailBillInstallment installment : installments) {
													EmailBillInstallmentEntity installmentEntity = new EmailBillInstallmentEntity();
													BeanUtils.copyProperties(installment, installmentEntity);
													installmentEntity.setEmailId(task.getEmailId());
													installmentEntity.setUserId(task.getUserId());
													billInstallmentRepository.saveBillInstallment(installmentEntity);
												}
											}

											// 查询消费记录
                							/*List<EmailBillShoppingSheetEntity> billItemEntities = loadBillShoppingSheetByCallApi(
                									emailBill.getBillId());*/
											// 保存消费记录
											//saveBillShoppingSheet(billEntity, billItemEntities,task.getUserId());

											//查询分期记录
											//List<EmailBillInstallmentEntity> installments = loadBillInstallmentByCallApi(emailBill.getBillId());
											//保存分期记录
											//saveBillInstallment(billEntity, installments);

										}

									}

								}
							}

						} catch (Exception e) {
							LOGGER.error("fetchBill failed. emailId:{}", task.getEmailId(), e);
						}


					}
				}

		);

	}

	private List<EmailBill> loadBillByCallApi(String taskId) throws IOException {
		EmailBillList emailBillList = emailClient.getBillstaskId(taskId);
//		EmailBillList emailBillList = emailClient.getBillsByTaskId(taskId);
		if (emailBillList != null) {

			return emailBillList.getBills();
		}
		return null;
	}
}


	/**
	 * 消费记录是分页查询。 loadBillItemsByCallApi:分页查询消费记录 <br/>
	 * size在魔蝎那边默认是2000，page默认1.<br/>
	 * 
	 * @author yuandong
	 * @param billId
	 * @return
	 * @throws IOException
	 * @since JDK 1.6
	 */
	/*private List<EmailBillShoppingSheetEntity> loadBillShoppingSheetByCallApi(String billId) throws IOException {
		List<EmailBillShoppingSheetEntity> billItemEntities = Lists.newArrayList();
		int size = 200;
		int page = 1;

		do {
			EmailBillShoppingSheetList creditBillItems = emailClient.getBillShoppingSheets(billId, page, size);
			if (creditBillItems != null && creditBillItems.getSize() > 0) {
				size = creditBillItems.getSize();
				LOGGER.info("loadBillShoppingSheetByCallApi success. billId:{}", billId);
				List<EmailBillShoppingSheet> shoppingSheets = creditBillItems.getShoppingSheets();
				for (EmailBillShoppingSheet shoppingSheet : shoppingSheets) {
					EmailBillShoppingSheetEntity billItemEntity = new EmailBillShoppingSheetEntity();
					BeanUtils.copyProperties(shoppingSheet, billItemEntity);
					billItemEntities.add(billItemEntity);
				}
			} else {
				size = 0;
			}
			page++;
		} while (size == 200);

		return billItemEntities;
	}*/
	
	
	
	/**
	 * 消费记录是分页查询。 loadBillItemsByCallApi:分页查询消费记录 <br/>
	 * size在魔蝎那边默认是2000，page默认1.<br/>
	 * 
	 * @author yuandong
	 * @param billId
	 * @return
	 * @throws IOException
	 * @since JDK 1.6
	 */
	/*private List<EmailBillInstallmentEntity> loadBillInstallmentByCallApi(String billId) throws IOException {
		List<EmailBillInstallmentEntity> billItemEntities = Lists.newArrayList();
		int size = 200;
		int page = 1;

		do {
			EmailBillInstallmentList creditBillItems = emailClient.getBillInstallments(billId, page, size);
			if (creditBillItems != null && creditBillItems.getSize() > 0) {
				size = creditBillItems.getSize();
				LOGGER.info("loadBillInstallmentByCallApi success. billId:{}", billId);
				List<EmailBillInstallment> installments = creditBillItems.getInstallments();
				for (EmailBillInstallment billInstallment : installments) {
					EmailBillInstallmentEntity billItemEntity = new EmailBillInstallmentEntity();
					BeanUtils.copyProperties(billInstallment, billItemEntity);
					billItemEntities.add(billItemEntity);
				}
			} else {
				size = 0;
			}
			page++;
		} while (size == 200);

		return billItemEntities;
	}*/

	// 保存消费记录
	/*private void saveBillShoppingSheet(EmailBillEntity billEntity, List<EmailBillShoppingSheetEntity> billItemEntities,String userId)
			throws Exception {
		if (billItemEntities != null && !billItemEntities.isEmpty()) {
			
			//先执行一次删除，防止已经有消费记录了
			billShoppingSheetRepository.deleteShoppingSheetByBillId(billEntity.getBillId(),userId);
//			if(billItemEntities.size()<10){
				for (EmailBillShoppingSheetEntity emailBillShoppingSheetEntity : billItemEntities) {
					// emailId和userId也放在消费记录里面，方便以后查询用
					emailBillShoppingSheetEntity.setEmailId(billEntity.getEmailId());
					emailBillShoppingSheetEntity.setUserId(billEntity.getUserId());
					// 保存
					billShoppingSheetRepository.saveBillShoppingSheet(emailBillShoppingSheetEntity,userId);
				}
//			}else{
//				
//			}
			
			
		}
		
		
	}*/
	
	
	// 保存分期记录
		/*private void saveBillInstallment(EmailBillEntity billEntity, List<EmailBillInstallmentEntity> billItemEntities)
				throws Exception {
			if (billItemEntities != null && !billItemEntities.isEmpty()) {
				
				//先执行一次删除，防止已经有消费记录了
				billInstallmentRepository.deleteInstallmentByBillId(billEntity.getBillId());
				
				for (EmailBillInstallmentEntity emailBillInstallmentEntity : billItemEntities) {
					// emailId和userId也放在消费记录里面，方便以后查询用
					emailBillInstallmentEntity.setEmailId(billEntity.getEmailId());
					emailBillInstallmentEntity.setUserId(billEntity.getUserId());
					// 保存
					billInstallmentRepository.saveBillInstallment(emailBillInstallmentEntity);
				}
			}
		}
}*/
